//
//  LivePlayViewController.swift
//  Swift_MyLive
//
//  Created by admin on 2017/5/12.
//  Copyright © 2017年 admin. All rights reserved.
//

import UIKit

class LivePlayViewController: UIViewController {

    var playerItem : AVPlayerItem?
    var player : AVPlayer?
    var playerLayer : AVPlayerLayer?
    var superView : UIView?
    var dataDic : NSDictionary?
    var closeBtn : UIButton?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        

        superView = UIView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: 300))
        superView?.backgroundColor = UIColor.black
        self.view.addSubview(superView!)

        let urlStr = self.dataDic?.stringForKey(key: "flv")
        
        let url = NSURL(string:"http://asp.cntv.lxdns.com/asp/hls/main/0303000a/3/default/1a9dcf9ec32a45f4834aec7d11514c4d/main.m3u8?maxbr=1200")
        
        
        playerItem = AVPlayerItem(url:url! as URL)
        //监听缓冲进度
        playerItem?.addObserver(self, forKeyPath:"loadedTimeRanges", options:NSKeyValueObservingOptions.new, context:nil)
        //监听状态改变
        playerItem?.addObserver(self, forKeyPath:"status", options:NSKeyValueObservingOptions.new, context:nil)
        
        
        //将视频源赋值给播放对象
        self.player = AVPlayer(playerItem:playerItem!)
        
        //初始化视频显示layler
        playerLayer = AVPlayerLayer(player: player!)
        
        // 设置显示模式
        playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspect
        playerLayer!.contentsScale = UIScreen.main.scale
        
        
        playerLayer!.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 300)
        
        superView!.layer.addSublayer(playerLayer!)
        
        self.player!.play()
        
        closeBtn = UIButton.init(frame: CGRect(x: WIDTH-50, y: 64, width: 40, height: 40))
        closeBtn?.addTarget(self, action:#selector(closeView) , for: .touchUpInside)
        closeBtn?.setTitle("关闭", for: .normal)
        self.view.addSubview(closeBtn!)
    }
    
    @objc func closeView() {
        
        self.dismiss(animated: true, completion: nil)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let playerItem = object as? AVPlayerItem else { return }
        if keyPath == "loadedTimeRanges"{
            // 缓冲进度 暂时不处理
      
            
        }else if keyPath == "status"{
            // 监听状态改变
            if playerItem.status == AVPlayerItemStatus.readyToPlay{
                // 只有在这个状态下才能播放
                //                self.player!.play()
                print("正在播放")
                
                SVProgressHUD.dismiss()
                
            }
        }
        else if playerItem.status == AVPlayerItemStatus.failed
        {
            SVProgressHUD.showError(withStatus: "加载异常！")
            
                SVProgressHUD.dismiss()
            
            print("加载异常")
        }
    }
    


func removeRevce()
{
    SVProgressHUD.dismiss()
    superView?.removeFromSuperview()
    playerItem?.removeObserver(self, forKeyPath: "loadedTimeRanges")
    playerItem?.removeObserver(self, forKeyPath: "status")
    
}
    
    deinit {
        self.removeRevce()
    }

   override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
